import $ from 'jquery'
import { BeeDraw } from '@/utils/print-util.js'
const Stringformat = function(B) {
  var A = Array.prototype.slice.call(arguments, 1)
  return B.replace(/\{(\d+)\}/g, function(C, D) {
    return A[D]
  })
}
const evil = function(fn) {
  var Fn = Function
  return new Fn('return ' + fn)()
}
/*eslint no-extend-native: ["error", { "exceptions": ["Date"] }]*/
Date.prototype.format = function(fmt) {
  var o = {
    'M+': this.getMonth() + 1,
    'd+': this.getDate(),
    'h+': this.getHours(),
    'm+': this.getMinutes(),
    's+': this.getSeconds(),
    'q+': Math.floor((this.getMonth() + 3) / 3),
    'S': this.getMilliseconds()
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
}
function JCPrint(n, vue) {
  this.username = n
  this.url = undefined
  this.ws = undefined
  this.status = 0
  this.cache = []
  this.listener = undefined
  this.vm = vue
}
JCPrint.prototype.setURL = function(url) {
  this.url = url
}
JCPrint.prototype.checkSocket = function() {
  if (this.status && this.ws) { return false }
  var b = /^[\d]{1,3}.[\d]{1,3}.[\d]{1,3}.[\d]{1,3}:[\d]{4,5}$/gi
  var c = /^ws:\/\/[\d]{1,3}.[\d]{1,3}.[\d]{1,3}.[\d]{1,3}:[\d]{4,5}$/gi
  this.url = this.vm.temp.url
  // this.url = '127.0.0.1:10001'
  if (!this.url || (!c.test(this.url) && !b.test(this.url))) {
    console.dir(this.vm.$message, '1')
    // this.vm.$message.closeAll() //  与断开连接提示有冲突  故而关闭
    this.vm.$message.warning('请检查打印服务地址')
    return false
  }

  if (this.url.indexOf('ws') < 0) {
    this.url = `ws://${this.url}`
  }
  try {
    this.ws = new WebSocket(this.url)
  } catch (ex) {
    this.ws = undefined
    return false
  }

  var _this = this
  this.ws.onopen = function() { _this.stateChange(1) }
  this.ws.onmessage = function(event) { _this.receive(event && event.data) }
  this.ws.onclose = function(event) { _this.stateChange(0) }
  return true
}
JCPrint.prototype.fire = function() {
  var _this = this
  if (!(_this.cache && _this.cache.length > 0) || _this.timeInterval) {
    return
  }
  _this.timeInterval = setInterval(function() {
    // console.log(new Date().format('yyyy-MM-dd HH:mm:ss'), 'index.js')
    // var _ws = $dlh.printer;
    if (_this.cache.length === 0) {
      clearInterval(_this.timeInterval)
      _this.timeInterval = undefined
      if (_this.timelen && _this.timelen >= 500) {
        _this.timelen = 200
      }
      return
    }
    if (!_this.ws) { return }
    if (!_this.status && _this.ws.readyState !== 1) {
      return
    }
    var content = _this.cache.splice(0, 1)[0]
    // console.log("正要输送打印内容：" , content);
    _this.ws.send(content)
  }, _this.timelen || 500)
}
JCPrint.prototype.firePush = function(d) {
  if (!this.ws) { return false }
  if (!this.status && this.ws.readyState !== 1) {
    return false
  }
  this.cache.push(d)
  this.fire()
  return true
}
JCPrint.prototype.connection = function(url) {
  this.status = 0
  this.url = url
  if (!this.checkSocket()) {
    this.stateChange(0)
    return
  }
  this.firePush(`{<${this.username}>}`)
}
JCPrint.prototype.unConnection = function(username) {
  if (this.ws) {
    this.send('~')
    // this.ws.close();
    //  this.ws = null;
  }

  this.status = 0
}
JCPrint.prototype.tryConnection = function(url) {
  if (!this.status) {
    this.connection(url)
    return
  }
  this.unConnection()
}
JCPrint.prototype.stateChange = function(b) {
  this.status = b

  if (!b) {
    delete this.ws; this.ws = undefined
    const printerIcon = document.getElementById('printer-icon')
    printerIcon.style.color = '#979FC1'
    this.vm.$message.info('与本地打印宝宝连接断开', 1000)
  } else {
    this.timelen = 500
    if (this.cache.length > 0) {
      /*	while(this.cache.length>0){
                  this.send(this.cache[0]);
                  this.cache=this.cache.slice(1);
              }*/

      this.fire()
    }
    const printerIcon = document.getElementById('printer-icon')
    printerIcon.style.color = '#01999F'
    document.getElementById('sys_007_print_map').style.display = 'flex'
    this.vm.$message.success('与本地打印宝宝连接成功', 1000)
  }
}
JCPrint.prototype.send = function(msg) {
  if (!this.ws) { return false }
  if (!this.status && this.ws.readyState !== 1) {
    this.cache.push(msg)
    return false
  }
  this.ws.send(msg)
  return true
}
JCPrint.prototype.registListener = function(listener) {
  this.listener = listener
}
JCPrint.prototype.clearListener = function() {
  this.listener = undefined
}
JCPrint.prototype.receive = function(msg) {
  // console.log('receive pbx msg', msg);
  if (this.listener) {
    this.listener(msg)
  }
}
JCPrint.prototype.process = function(printcmd, doc, row, items) {
  if (doc.doc) {
    // 新版打印处理
    var orderDetails = items
    row.details = orderDetails
    var source = JSON.parse(JSON.stringify(row))
    var printer = {
      'printer': doc.printer
    }
    if (!(source instanceof Array) && source instanceof Object) {
      var cmds = new BeeDraw(false).draw(doc, source)
      $.extend(cmds, printer)
      $.extend(printcmd, cmds)
      delete printcmd.els
      // console.log('11', printcmd)
    }
    return
  }
  var tmpbl = false
  delete printcmd.items
  var arrayMap = {}
  for (var i in doc.items) {
    var el = doc.items[i]
    if (el.etype && el.arrayname && !el.isarray) {
      if (el.isfixed === 'y') {
        el.y = arrayMap[el.arrayname].h + (el.top || 0) + (el.height || 0)
        el.y1 = el.y
        delete el.isfixed
      } else if (el.isfixed === 'x') {
        el.y = arrayMap[el.arrayname].h + (el.top || 0)
        el.y1 = el.y + (el.height || 0)
        delete el.isfixed
      } else {
        el.y = arrayMap[el.arrayname].l
        el.y1 = arrayMap[el.arrayname].h + el.size
      }
      delete el.arrayname
      if (el.etype === 1 && el.y1) {
        delete el.y1
      }
    }
    if (el.etype === 2 && !el.isarray) {
      printcmd.elements.push(el)
      continue
    }
    if (el.etype === 0) {
      arrayMap[el.arrayname] = { l: el.l, h: el.h }
      continue
    }
    if (el.isarray) {
      if (items) {
        if (!el.vtype) {
          if (el.etype === 2) {
            var h = 0; var c = el.y
            for (var j in items) {
              var ditem = items[j]
              var tempel = {}
              // $.extend(tempel, el)
              tempel = { ...el } // 现
              h += tempel.height
              tempel.y = tempel.y1 = (c + h)
              delete tempel.height
              delete tempel.isarray

              printcmd.elements.push(tempel)
            }
          }
          continue
        }

        h = 0
        for (j in items) {
          ditem = items[j]
          tempel = {}
          // $.extend(tempel, el)
          tempel = { ...el } // 现
          tempel.y = (h + (el.y || 0))

          h += el.height || 0
          delete tempel.height
          delete tempel.isarray
          if (tempel.vtype === 1) {
            delete tempel.vtype
            tempel.evalue = tempel.pt
            delete tempel.pt
            printcmd.elements.push(tempel)
          } else if (tempel.vtype === 2) {
            delete tempel.vtype
            tempel.evalue = ditem[tempel.pt] || ''
            if (tempel.eval) {
              tempel.evalue = evil(Stringformat(tempel.eval, tempel.evalue)) // 原
              // tempel.evalue = Stringformat(tempel.eval, tempel.evalue)
            }
            delete tempel.pt
            printcmd.elements.push(tempel)
          }
        }
        if (el.arrayname) {
          arrayMap[el.arrayname].h += h
        }
      }
      continue
    }
    if (el.vtype === 1) {
      if (el.tmp && tmpbl === false) {
        continue
      }
      delete el.vtype
      el.evalue = el.pt
      delete el.pt
      printcmd.elements.push(el)
    } else if (el.vtype === 2) {
      delete el.vtype
      if (el.pt) {
        el.evalue = row[el.pt] || ''
        if (el.eval) {
          // el.evalue = eval(String.format(el.eval, el.evalue))
          // el.evalue = Stringformat(el.eval, el.evalue)
          // el.evalue = eval(Stringformat(el.eval, el.evalue))
          console.log(Stringformat(el.eval, el.evalue))
          console.log(new Date().format('yyyy-MM-dd HH:mm:ss'))
          el.evalue = evil(Stringformat(el.eval, el.evalue))
        }
        delete el.pt
      } else {
        if (el.eval) {
          // el.evalue = eval(String.format(el.eval, JSON.stringify(row)))
          // el.evalue = Stringformat(el.eval, JSON.stringify(row))
          el.evalue = evil(Stringformat(el.eval, JSON.stringify(row)))
        }
      }
      printcmd.elements.push(el)
    }
  }
}
export default JCPrint
